<template>
  <div class="app-container">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="logo">
        <span class="iconify" data-icon="mdi:medal" style="color: white;"></span>
        运动会管理系统
      </div>
      <div class="flex-grow"></div>
      <div class="flex items-center gap-6">
        <div class="flex items-center gap-2">
          <img id="img-head" src="img/jstu1.webp">
          <span class="text-white text-sm">{{ currentUser?.realName || '管理员' }}</span>
        </div>
        <div class="flex items-center gap-2">
          <a href="javascript:void(0)" class="denglu" @click="handleLogout">退出登录</a>
        </div>
      </div>
    </header>

    <!-- 左侧导航栏 -->
    <nav class="sidebar">
      <div class="menu-item" :class="{ active: $route.path === '/admin' }">
        <span class="iconify" data-icon="mdi:view-dashboard"></span>
        <a @click="$router.push('/admin')">系统管理</a>
      </div>
      <div class="menu-item" :class="{ active: $route.path === '/admin/users' }">
        <span class="iconify" data-icon="mdi:account-group"></span>
        <a @click="$router.push('/admin/users')">用户管理</a>
      </div>
      <div class="menu-item" :class="{ active: $route.path === '/admin/projects' }">
        <span class="iconify" data-icon="mdi:clipboard-list"></span>
        <a @click="$router.push('/admin/projects')">项目管理</a>
      </div>
      <div class="menu-item" :class="{ active: $route.path === '/admin/schedule' }">
        <span class="iconify" data-icon="mdi:calendar-clock"></span>
        <a @click="$router.push('/admin/schedule')">赛程管理</a>
      </div>
      <div class="menu-item" :class="{ active: $route.path === '/admin/referee' }">
        <span class="iconify" data-icon="mdi:whistle"></span>
        <a @click="$router.push('/admin/referee')">裁判管理</a>
      </div>
      <div class="menu-item active">
        <span class="iconify" data-icon="mdi:clipboard-text"></span>
        执裁记录
      </div>
    </nav>

    <!-- 主要内容 -->
    <main class="content">
      <!-- 面包屑导航 -->
      <el-breadcrumb class="breadcrumb" separator="/">
        <el-breadcrumb-item :to="{ path: '/admin' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/admin/referee' }">裁判管理</el-breadcrumb-item>
        <el-breadcrumb-item>执裁记录</el-breadcrumb-item>
      </el-breadcrumb>

      <div class="main-content-header">
        <h1 class="text-2xl font-medium">裁判执裁记录</h1>
        <div class="header-actions">
          <el-button type="success" size="small" @click="handleExport">
            <i class="el-icon-download"></i> 导出记录
          </el-button>
          <el-button type="info" size="small" @click="handleRefresh">
            <i class="el-icon-refresh"></i> 刷新数据
          </el-button>
        </div>
      </div>

      <!-- 统计信息卡片 -->
      <div class="statistics-container">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-icon total">
                <i class="el-icon-document"></i>
              </div>
              <div class="stat-info">
                <div class="stat-title">总执裁次数</div>
                <div class="stat-value">{{ statistics.totalRecords || 0 }}</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-icon completed">
                <i class="el-icon-check"></i>
              </div>
              <div class="stat-info">
                <div class="stat-title">已完成场次</div>
                <div class="stat-value">{{ statistics.completedRecords || 0 }}</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-icon hours">
                <i class="el-icon-time"></i>
              </div>
              <div class="stat-info">
                <div class="stat-title">总执裁时长</div>
                <div class="stat-value">{{ statistics.totalHours || 0 }}小时</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-icon rating">
                <i class="el-icon-star-on"></i>
              </div>
              <div class="stat-info">
                <div class="stat-title">平均评分</div>
                <div class="stat-value">{{ statistics.avgRating || 0 }}分</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 裁判工作负载分析 -->
      <div class="workload-analysis">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>裁判工作负载分析</span>
              <el-button type="text" @click="refreshWorkloadData">
                <i class="el-icon-refresh"></i> 刷新
              </el-button>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="chart-container">
                <div class="chart-title">执裁次数排行</div>
                <div class="ranking-list">
                  <div
                    v-for="(item, index) in workloadRanking"
                    :key="item.refereeId"
                    class="ranking-item">
                    <div class="ranking-number">{{ index + 1 }}</div>
                    <div class="ranking-info">
                      <div class="referee-name">{{ item.refereeName }}</div>
                      <div class="referee-level">{{ item.levelName }}</div>
                    </div>
                    <div class="ranking-value">
                      <span class="count">{{ item.recordCount }}次</span>
                      <el-progress
                        :percentage="(item.recordCount / maxRecordCount) * 100"
                        :stroke-width="6"
                        :show-text="false">
                      </el-progress>
                    </div>
                  </div>
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="chart-container">
                <div class="chart-title">工作时长分布</div>
                <div class="time-distribution">
                  <div
                    v-for="(item, index) in timeDistribution"
                    :key="index"
                    class="time-item">
                    <div class="time-range">{{ item.range }}</div>
                    <div class="time-count">{{ item.count }}人</div>
                    <div class="time-bar">
                      <div
                        class="time-bar-fill"
                        :style="{ width: (item.count / maxTimeCount) * 100 + '%' }">
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </div>

      <!-- 筛选区域 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm" size="small">
          <el-form-item label="裁判">
            <el-select
              v-model="searchForm.refereeId"
              placeholder="请选择裁判"
              clearable
              style="width: 180px"
              filterable>
              <el-option
                v-for="referee in refereeList"
                :key="referee.id"
                :label="referee.realName"
                :value="referee.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="项目">
            <el-select
              v-model="searchForm.projectId"
              placeholder="请选择项目"
              clearable
              style="width: 180px"
              filterable>
              <el-option
                v-for="project in projectList"
                :key="project.id"
                :label="project.name"
                :value="project.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="执裁角色">
            <el-select v-model="searchForm.role" placeholder="请选择角色" clearable style="width: 150px">
              <el-option label="主裁判" value="主裁判"></el-option>
              <el-option label="副裁判" value="副裁判"></el-option>
              <el-option label="记录员" value="记录员"></el-option>
              <el-option label="计时员" value="计时员"></el-option>
              <el-option label="检录员" value="检录员"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="执裁时间">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 240px">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
              <el-option label="已完成" value="已完成"></el-option>
              <el-option label="进行中" value="进行中"></el-option>
              <el-option label="已取消" value="已取消"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :loading="loading">
              <i class="el-icon-search"></i> 搜索
            </el-button>
            <el-button @click="handleReset">
              <i class="el-icon-refresh"></i> 重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 执裁记录表格 -->
      <div class="table-container">
        <el-table
          :data="tableData"
          v-loading="loading"
          stripe
          border
          style="width: 100%">
          <el-table-column prop="id" label="记录ID" width="80" align="center"></el-table-column>
          <el-table-column prop="refereeName" label="裁判姓名" width="120" align="center"></el-table-column>
          <el-table-column prop="refereeLevel" label="资质等级" width="120" align="center">
            <template #default="scope">
              <el-tag :type="getLevelTagType(scope.row.refereeLevel)" size="small">
                {{ scope.row.refereeLevel }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="projectName" label="项目名称" width="150" align="center" show-overflow-tooltip></el-table-column>
          <el-table-column prop="projectType" label="项目类型" width="100" align="center">
            <template #default="scope">
              <el-tag :type="getProjectTypeTag(scope.row.projectType)" size="small">
                {{ scope.row.projectType }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="role" label="执裁角色" width="100" align="center">
            <template #default="scope">
              <el-tag type="info" size="small">{{ scope.row.role }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="eventDate" label="比赛日期" width="120" align="center">
            <template #default="scope">
              {{ formatDate(scope.row.eventDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="startTime" label="开始时间" width="100" align="center">
            <template #default="scope">
              {{ scope.row.startTime || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="endTime" label="结束时间" width="100" align="center">
            <template #default="scope">
              {{ scope.row.endTime || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="duration" label="执裁时长" width="100" align="center">
            <template #default="scope">
              {{ calculateDuration(scope.row.startTime, scope.row.endTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="location" label="比赛地点" width="150" align="center" show-overflow-tooltip></el-table-column>
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag :type="getStatusTagType(scope.row.status)" size="small">
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="rating" label="评分" width="120" align="center">
            <template #default="scope">
              <div v-if="scope.row.rating">
                <el-rate
                  v-model="scope.row.rating"
                  disabled
                  text-color="#ff9900"
                  show-score>
                </el-rate>
              </div>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" align="center" fixed="right">
            <template #default="scope">
              <el-button-group size="mini">
                <el-button type="primary" icon="el-icon-view" @click="handleViewDetail(scope.row)">详情</el-button>
                <el-button v-if="scope.row.status === '已完成'" type="success" icon="el-icon-star-on" @click="handleEvaluate(scope.row)">评价</el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页控制 -->
        <div class="pagination-container">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total">
          </el-pagination>
        </div>
      </div>

      <!-- 记录详情对话框 -->
      <el-dialog
        title="执裁记录详情"
        v-model="detailDialogVisible"
        width="800px">
        <div v-if="currentRecord" class="record-detail">
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <span class="label">裁判姓名：</span>
                <span class="value">{{ currentRecord.refereeName }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="label">资质等级：</span>
                <el-tag :type="getLevelTagType(currentRecord.refereeLevel)" size="small">
                  {{ currentRecord.refereeLevel }}
                </el-tag>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <span class="label">项目名称：</span>
                <span class="value">{{ currentRecord.projectName }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="label">项目类型：</span>
                <el-tag :type="getProjectTypeTag(currentRecord.projectType)" size="small">
                  {{ currentRecord.projectType }}
                </el-tag>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <span class="label">执裁角色：</span>
                <el-tag type="info" size="small">{{ currentRecord.role }}</el-tag>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="label">比赛地点：</span>
                <span class="value">{{ currentRecord.location }}</span>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="detail-item">
                <span class="label">比赛日期：</span>
                <span class="value">{{ formatDate(currentRecord.eventDate) }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="detail-item">
                <span class="label">开始时间：</span>
                <span class="value">{{ currentRecord.startTime || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="detail-item">
                <span class="label">结束时间：</span>
                <span class="value">{{ currentRecord.endTime || '-' }}</span>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <span class="label">执裁时长：</span>
                <span class="value">{{ calculateDuration(currentRecord.startTime, currentRecord.endTime) }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="label">执裁状态：</span>
                <el-tag :type="getStatusTagType(currentRecord.status)" size="small">
                  {{ currentRecord.status }}
                </el-tag>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20" v-if="currentRecord.rating">
            <el-col :span="12">
              <div class="detail-item">
                <span class="label">执裁评分：</span>
                <el-rate
                  v-model="currentRecord.rating"
                  disabled
                  text-color="#ff9900"
                  show-score>
                </el-rate>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="label">评价时间：</span>
                <span class="value">{{ formatDateTime(currentRecord.ratingTime) }}</span>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20" v-if="currentRecord.remarks">
            <el-col :span="24">
              <div class="detail-item">
                <span class="label">备注信息：</span>
                <span class="value">{{ currentRecord.remarks }}</span>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-dialog>

      <!-- 裁判评价对话框 -->
      <el-dialog
        title="裁判执裁评价"
        v-model="evaluateDialogVisible"
        width="500px">
        <el-form :model="evaluateForm" :rules="evaluateFormRules" ref="evaluateFormRef" label-width="100px">
          <el-form-item label="裁判姓名">
            <el-input v-model="evaluateForm.refereeName" disabled></el-input>
          </el-form-item>
          <el-form-item label="执裁项目">
            <el-input v-model="evaluateForm.projectName" disabled></el-input>
          </el-form-item>
          <el-form-item label="执裁角色">
            <el-input v-model="evaluateForm.role" disabled></el-input>
          </el-form-item>
          <el-form-item label="评分" prop="rating">
            <el-rate
              v-model="evaluateForm.rating"
              show-text
              :texts="['很差', '较差', '一般', '良好', '优秀']">
            </el-rate>
          </el-form-item>
          <el-form-item label="评价内容" prop="comment">
            <el-input
              v-model="evaluateForm.comment"
              type="textarea"
              :rows="4"
              placeholder="请输入评价内容">
            </el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="evaluateDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSaveEvaluation" :loading="saveLoading">提交评价</el-button>
          </div>
        </template>
      </el-dialog>
    </main>
  </div>
</template>

<script>
import {
  getRefereePage,
  getRefereeStatistics,
  submitRefereeRating
} from '@/api/referee'
import {
  getProjectPage
} from '@/api/project'
import { useAuthStore } from '@/stores/auth'

export default {
  name: 'RefereeRecords',
  setup() {
    const authStore = useAuthStore()
    return {
      authStore
    }
  },
  data() {
    return {
      // 当前用户信息
      currentUser: null,

      // 搜索表单
      searchForm: {
        refereeId: null,
        projectId: null,
        role: '',
        dateRange: [],
        status: ''
      },

      // 裁判列表
      refereeList: [],
      // 项目列表
      projectList: [],

      // 统计信息
      statistics: {
        totalRecords: 0,
        completedRecords: 0,
        totalHours: 0,
        avgRating: 0
      },

      // 工作负载分析数据
      workloadRanking: [],
      timeDistribution: [],
      maxRecordCount: 0,
      maxTimeCount: 0,

      // 表格数据
      tableData: [],
      loading: false,

      // 分页信息
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },

      // 详情对话框
      detailDialogVisible: false,
      currentRecord: null,

      // 评价对话框
      evaluateDialogVisible: false,
      evaluateForm: {
        recordId: null,
        refereeId: null,
        refereeName: '',
        projectName: '',
        role: '',
        rating: 5,
        comment: ''
      },
      evaluateFormRules: {
        rating: [
          { required: true, message: '请选择评分', trigger: 'change' }
        ],
        comment: [
          { required: true, message: '请输入评价内容', trigger: 'blur' },
          { min: 10, max: 500, message: '评价内容长度在 10 到 500 个字符', trigger: 'blur' }
        ]
      },
      saveLoading: false
    }
  },

  created() {
    // 获取当前用户信息
    this.currentUser = this.authStore.userInfo || JSON.parse(localStorage.getItem('user'))
    // 初始化数据
    this.initData()
  },

  methods: {
    // 初始化数据
    async initData() {
      await this.loadRefereeList()
      await this.loadProjectList()
      await this.loadStatistics()
      await this.loadWorkloadData()
      this.loadData()
    },

    // 加载裁判列表
    async loadRefereeList() {
      try {
        const response = await getRefereePage(1, 1000, { isActive: true })
        if (response.code === 200) {
          this.refereeList = response.data.records || []
        }
      } catch (error) {
        console.error('加载裁判列表失败:', error)
      }
    },

    // 加载项目列表
    async loadProjectList() {
      try {
        const response = await getProjectPage(1, 1000, {})
        if (response.code === 200) {
          this.projectList = response.data.records || []
        }
      } catch (error) {
        console.error('加载项目列表失败:', error)
      }
    },

    // 加载统计信息
    async loadStatistics() {
      try {
        const response = await getRefereeStatistics()
        if (response.code === 200) {
          // 这里应该从API获取执裁记录的统计信息
          // 暂时模拟数据
          this.statistics = {
            totalRecords: response.data.totalRecords || 0,
            completedRecords: response.data.completedRecords || 0,
            totalHours: response.data.totalHours || 0,
            avgRating: response.data.avgRating || 0
          }
        }
      } catch (error) {
        console.error('加载统计信息失败:', error)
      }
    },

    // 加载工作负载数据
    async loadWorkloadData() {
      try {
        // 模拟执裁次数排行数据
        this.workloadRanking = [
          { refereeId: 1, refereeName: '张三', levelName: '国家级', recordCount: 15 },
          { refereeId: 2, refereeName: '李四', levelName: '省级', recordCount: 12 },
          { refereeId: 3, refereeName: '王五', levelName: '市级', recordCount: 10 },
          { refereeId: 4, refereeName: '赵六', levelName: '校级', recordCount: 8 },
          { refereeId: 5, refereeName: '钱七', levelName: '实习', recordCount: 6 }
        ]

        // 模拟工作时长分布数据
        this.timeDistribution = [
          { range: '0-10小时', count: 5 },
          { range: '10-20小时', count: 12 },
          { range: '20-30小时', count: 8 },
          { range: '30-40小时', count: 3 },
          { range: '40小时以上', count: 2 }
        ]

        // 计算最大值用于进度条
        this.maxRecordCount = Math.max(...this.workloadRanking.map(item => item.recordCount))
        this.maxTimeCount = Math.max(...this.timeDistribution.map(item => item.count))
      } catch (error) {
        console.error('加载工作负载数据失败:', error)
      }
    },

    // 加载数据
    async loadData() {
      this.loading = true
      try {
        const params = {
          ...this.searchForm,
          currentPage: this.pagination.currentPage,
          pageSize: this.pagination.pageSize
        }

        // 处理日期范围
        if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
          params.startDate = this.searchForm.dateRange[0]
          params.endDate = this.searchForm.dateRange[1]
        }

        // 模拟API调用 - 实际应该调用getRefereeRecords或getRefereeHistory
        // const response = await getRefereeRecords(null, params)

        // 模拟数据
        const mockData = this.generateMockData(params)
        this.tableData = mockData.records
        this.pagination.total = mockData.total

      } catch (error) {
        console.error('获取执裁记录失败:', error)
        this.$message.error('获取数据失败')
      } finally {
        this.loading = false
      }
    },

    // 生成模拟数据
    generateMockData(params) {
      const records = []
      const total = 50

      for (let i = 1; i <= total; i++) {
        const referee = this.refereeList[Math.floor(Math.random() * this.refereeList.length)] || { realName: '裁判' + i }
        const project = this.projectList[Math.floor(Math.random() * this.projectList.length)] || { name: '项目' + i, type: '田径' }
        const roles = ['主裁判', '副裁判', '记录员', '计时员', '检录员']
        const statuses = ['已完成', '进行中', '已取消']

        const eventDate = new Date()
        eventDate.setDate(eventDate.getDate() - Math.floor(Math.random() * 30))

        const startTime = this.generateRandomTime()
        const endTime = this.generateRandomTime(startTime)
        const status = statuses[Math.floor(Math.random() * statuses.length)]

        records.push({
          id: i,
          refereeId: referee.id || i,
          refereeName: referee.realName,
          refereeLevel: referee.levelName || '校级',
          projectName: project.name,
          projectType: project.type,
          role: roles[Math.floor(Math.random() * roles.length)],
          eventDate: eventDate.toISOString().split('T')[0],
          startTime: startTime,
          endTime: endTime,
          location: '体育场' + Math.floor(Math.random() * 10) + '号场地',
          status: status,
          rating: status === '已完成' ? Math.floor(Math.random() * 5) + 1 : null,
          ratingTime: status === '已完成' ? new Date().toISOString() : null,
          remarks: Math.random() > 0.5 ? '执裁认真负责，专业水平高' : null
        })
      }

      // 应用筛选条件
      let filteredRecords = records
      if (params.refereeId) {
        filteredRecords = filteredRecords.filter(r => r.refereeId === params.refereeId)
      }
      if (params.projectId) {
        filteredRecords = filteredRecords.filter(r => r.projectName.includes(params.projectId))
      }
      if (params.role) {
        filteredRecords = filteredRecords.filter(r => r.role === params.role)
      }
      if (params.status) {
        filteredRecords = filteredRecords.filter(r => r.status === params.status)
      }
      if (params.startDate && params.endDate) {
        filteredRecords = filteredRecords.filter(r =>
          r.eventDate >= params.startDate && r.eventDate <= params.endDate
        )
      }

      // 分页
      const start = (params.currentPage - 1) * params.pageSize
      const end = start + params.pageSize

      return {
        records: filteredRecords.slice(start, end),
        total: filteredRecords.length
      }
    },

    // 生成随机时间
    generateRandomTime(afterTime = null) {
      const hour = afterTime ?
        parseInt(afterTime.split(':')[0]) + Math.floor(Math.random() * 3) :
        8 + Math.floor(Math.random() * 10)
      const minute = Math.floor(Math.random() * 60)
      return `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`
    },

    // 搜索
    handleSearch() {
      this.pagination.currentPage = 1
      this.loadData()
    },

    // 重置搜索
    handleReset() {
      this.searchForm = {
        refereeId: null,
        projectId: null,
        role: '',
        dateRange: [],
        status: ''
      }
      this.handleSearch()
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.loadData()
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.loadData()
    },

    // 查看详情
    handleViewDetail(row) {
      this.currentRecord = row
      this.detailDialogVisible = true
    },

    // 评价裁判
    handleEvaluate(row) {
      this.evaluateForm = {
        recordId: row.id,
        refereeId: row.refereeId,
        refereeName: row.refereeName,
        projectName: row.projectName,
        role: row.role,
        rating: 5,
        comment: ''
      }
      this.evaluateDialogVisible = true
    },

    // 保存评价
    handleSaveEvaluation() {
      this.$refs.evaluateFormRef.validate(async (valid) => {
        if (valid) {
          this.saveLoading = true
          try {
            const response = await submitRefereeRating(this.evaluateForm)
            if (response.code === 200) {
              this.$message.success('评价提交成功')
              this.evaluateDialogVisible = false
              this.loadData()
            } else {
              this.$message.error(response.message || '评价提交失败')
            }
          } catch (error) {
            console.error('提交评价失败:', error)
            this.$message.error('评价提交失败')
          } finally {
            this.saveLoading = false
          }
        }
      })
    },

    // 导出记录
    async handleExport() {
      try {
        const params = { ...this.searchForm }
        if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
          params.startDate = this.searchForm.dateRange[0]
          params.endDate = this.searchForm.dateRange[1]
        }

        // 调用导出API
        // const response = await exportRefereeRecords(null, params)

        // 模拟导出
        this.$message.success('导出成功')
      } catch (error) {
        console.error('导出失败:', error)
        this.$message.error('导出失败')
      }
    },

    // 刷新数据
    handleRefresh() {
      this.loadData()
      this.loadStatistics()
      this.loadWorkloadData()
    },

    // 刷新工作负载数据
    refreshWorkloadData() {
      this.loadWorkloadData()
    },

    // 退出登录
    handleLogout() {
      this.$confirm('确定要退出登录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 清除用户信息
        this.authStore.logout()
        localStorage.removeItem('user')
        localStorage.removeItem('token')
        // 跳转到登录页
        this.$router.push('/login')
      })
    },

    // 获取资质等级标签类型
    getLevelTagType(levelName) {
      const typeMap = {
        '国家级': 'danger',
        '省级': 'warning',
        '市级': 'primary',
        '校级': 'success',
        '实习': 'info'
      }
      return typeMap[levelName] || 'primary'
    },

    // 获取项目类型标签类型
    getProjectTypeTag(type) {
      const typeMap = {
        '田径': 'success',
        '球类': 'primary',
        '游泳': 'warning',
        '体操': 'danger',
        '武术': 'info'
      }
      return typeMap[type] || 'primary'
    },

    // 获取状态标签类型
    getStatusTagType(status) {
      const typeMap = {
        '已完成': 'success',
        '进行中': 'warning',
        '已取消': 'info'
      }
      return typeMap[status] || 'primary'
    },

    // 计算执裁时长
    calculateDuration(startTime, endTime) {
      if (!startTime || !endTime) return '-'

      const [startHour, startMin] = startTime.split(':').map(Number)
      const [endHour, endMin] = endTime.split(':').map(Number)

      const startMinutes = startHour * 60 + startMin
      const endMinutes = endHour * 60 + endMin

      const duration = endMinutes - startMinutes
      if (duration <= 0) return '-'

      const hours = Math.floor(duration / 60)
      const minutes = duration % 60

      return `${hours}小时${minutes > 0 ? minutes + '分钟' : ''}`
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return '-'
      return new Date(date).toLocaleDateString('zh-CN')
    },

    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return '-'
      return new Date(dateTime).toLocaleString('zh-CN')
    }
  }
}
</script>

<style scoped>
/* 基础样式 */
* {
  font-family: 'PingFang SC', -apple-system, BlinkMacSystemFont, sans-serif;
}

body {
  background-color: #f0f2f5;
  color: #1a1a1a;
  margin: 0;
}

/* 容器布局 */
.app-container {
  max-width: 1440px;
  margin: 0 auto;
  display: grid;
  grid-template-columns: 240px 1fr;
  grid-template-rows: 64px 1fr;
  min-height: 100vh;
  background-color: #F5F7FA;
}

/* 顶部导航栏 */
.header {
  grid-column: 1 / -1;
  background-color: #2C5AA0;
  display: flex;
  align-items: center;
  padding: 0 24px;
}

.logo {
  font-size: 18px;
  font-weight: bold;
  color: white;
  display: flex;
  align-items: center;
  gap: 8px;
}

.flex-grow {
  flex-grow: 1;
}

.flex {
  display: flex;
}

.items-center {
  align-items: center;
}

.gap-6 {
  gap: 24px;
}

.gap-2 {
  gap: 8px;
}

/* 左侧导航栏 */
.sidebar {
  background-color: white;
  padding: 16px 0;
  border-right: 1px solid #e4e7ed;
}

.menu-item {
  padding: 12px 24px;
  color: #555;
  display: flex;
  align-items: center;
  gap: 12px;
  transition: all 0.3s;
  cursor: pointer;
}

.menu-item.active,
.menu-item:hover {
  background-color: #e8eff9;
  color: #2C5AA0;
  border-right: 3px solid #2C5AA0;
}

/* 主内容区 */
.content {
  padding: 24px;
  display: grid;
  grid-template-rows: auto auto 1fr;
  gap: 24px;
  overflow-y: auto;
}

/* 面包屑 */
.breadcrumb {
  margin-bottom: 16px;
}

.main-content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 统计卡片 */
.statistics-container {
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  gap: 20px;
  transition: all 0.3s;
  cursor: pointer;
  height: 100%;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  width: 70px;
  height: 70px;
  border-radius: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
  color: white;
  flex-shrink: 0;
}

.stat-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.completed {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.hours {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.rating {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}

.stat-info {
  flex: 1;
}

.stat-title {
  font-size: 15px;
  color: #606266;
  margin-bottom: 8px;
  font-weight: 500;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
}

/* 工作负载分析 */
.workload-analysis {
  margin-bottom: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  padding: 20px;
}

.chart-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 20px;
  text-align: center;
}

/* 排行列表 */
.ranking-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.ranking-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 6px;
  transition: all 0.3s;
}

.ranking-item:hover {
  background-color: #e8f4fd;
}

.ranking-number {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: #409eff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 14px;
}

.ranking-info {
  flex: 1;
}

.referee-name {
  font-weight: 500;
  color: #303133;
}

.referee-level {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}

.ranking-value {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
  min-width: 120px;
}

.count {
  font-weight: 500;
  color: #409eff;
}

/* 时间分布 */
.time-distribution {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.time-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.time-range {
  width: 100px;
  font-size: 14px;
  color: #606266;
}

.time-count {
  width: 60px;
  font-weight: 500;
  color: #409eff;
  text-align: right;
}

.time-bar {
  flex: 1;
  height: 20px;
  background-color: #f0f2f5;
  border-radius: 10px;
  overflow: hidden;
}

.time-bar-fill {
  height: 100%;
  background: linear-gradient(90deg, #409eff 0%, #67c23a 100%);
  transition: width 0.5s ease;
}

/* 搜索区域 */
.search-bar {
  background: white;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border: 1px solid #e4e7ed;
  margin-bottom: 24px;
}

/* 表格容器 */
.table-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border: 1px solid #e4e7ed;
  padding: 24px;
  overflow: hidden;
}

/* 分页容器 */
.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 记录详情样式 */
.record-detail {
  padding: 24px;
}

.detail-item {
  display: flex;
  margin-bottom: 20px;
  align-items: center;
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.detail-item:hover {
  background-color: #e9ecef;
}

.detail-item .label {
  width: 120px;
  font-weight: 500;
  color: #606266;
}

.detail-item .value {
  flex: 1;
  color: #303133;
  font-weight: 500;
}

/* 头像和退出登录 */
#img-head {
  height: 40px;
  width: 40px;
  border-radius: 50px;
}

.denglu {
  color: white;
  font-size: 15px;
  text-decoration: none;
}

.denglu:hover {
  color: #F44346;
}

.text-sm {
  font-size: 14px;
}

.text-white {
  color: white;
}

/* Element UI 样式调整 */
.el-card {
  margin-bottom: 0;
}

.el-card__header {
  padding: 16px 20px;
  border-bottom: 1px solid #e4e7ed;
}

.el-table {
  margin-top: 16px;
}

.el-table th {
  background-color: #fafafa !important;
}

.el-form-item {
  margin-bottom: 0;
}

.el-rate {
  display: inline-block;
}

.el-progress {
  width: 80px;
}

.el-progress-bar__outer {
  background-color: #e4e7ed;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .stat-card {
    padding: 16px;
  }

  .stat-icon {
    width: 50px;
    height: 50px;
    font-size: 20px;
  }

  .stat-value {
    font-size: 24px;
  }
}

@media (max-width: 768px) {
  .app-container {
    grid-template-columns: 1fr;
  }

  .sidebar {
    display: none;
  }

  .statistics-container .el-col {
    margin-bottom: 16px;
  }

  .search-bar .el-form-item {
    margin-bottom: 16px;
  }

  .table-container {
    overflow-x: auto;
  }

  .workload-analysis .el-col {
    margin-bottom: 20px;
  }

  .ranking-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .ranking-value {
    width: 100%;
  }

  .time-item {
    flex-wrap: wrap;
  }

  .time-range {
    width: auto;
  }
}
</style>